package com.maycari.captainbi.scheduled;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.maycari.captainbi.common.exception.BusinessException;
import com.maycari.captainbi.data.dto.*;
import com.maycari.captainbi.service.Captain15Service;
import com.maycari.captainbi.service.Captain16Service;
import com.maycari.captainbi.service.Captain17Service;
import com.maycari.captainbi.util.CaptainBIUtil;
import com.maycari.captainbi.util.MaycariRedis;
import com.maycari.tool.utils.DateUtil;
import com.maycari.tool.utils.ThreadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class Task16_17 implements ApplicationRunner {

    @Autowired
    private MaycariRedis maycariRedis;

    private static String start_time_str = "2021-02-18 00:00:00";

    private static String dataKey = "MAYCARI:DATAKEY16";

    private static String action = "http://cronapi.captainbi.com/index.php?m=cronapi&c=order&a=getOrderJavList";

    private static String dataKey2 = "MAYCARI:DATAKEY17";

    private static String action2 = "http://cronapi.captainbi.com/index.php?m=cronapi&c=order&a=getOrderJavItemList";

    @Autowired
    private Captain16Service captain16Service;
    @Autowired
    private Captain17Service captain17Service;

    //@Scheduled(cron = "0 0 1 * * ?")
    public void task() {
        System.out.println(1);

    }

    private void getData() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

        int page = 1;
        int page_size = 100;

        //订单最后更新时间（开始）
        Date start_time = maycariRedis.get(dataKey);
        if (start_time == null) {
            start_time = DateUtil.parse(start_time_str, DateUtil.PATTERN_DATETIME);
        }

        while (true) {
            JSONArray jsonArray = new JSONArray();
            Date now = new Date();
            //一天
            Date end_time = DateUtil.minusSeconds(DateUtil.plusDays(start_time, 1), 1);

            if (end_time.after(now)) {
                break;
            }
            while (true) {
                ThreadUtil.sleep(1000);
                TreeMap<String, String> params = new TreeMap<>();
                params.put("page", String.valueOf(page));
                params.put("page_size", String.valueOf(page_size));
                params.put("start_order_time", simpleDateFormat.format(start_time));
                params.put("end_order_time", simpleDateFormat.format(end_time));
                String result = CaptainBIUtil.sendRequest(action, params);
                JSONObject jsonObject = JSON.parseObject(result, Feature.OrderedField);
                int code = jsonObject.getIntValue("code");
                if (code == 200) {
                    JSONArray data = jsonObject.getJSONArray("data");
                    if (data != null && data.size() > 0) {
                        if (data.size() >= 100) {
                            //可能还有数据  继续请求
                            jsonArray.addAll(data);
                            page++;
                        } else {
                            jsonArray.addAll(data);
                            break;
                        }
                    } else {
                        break;
                    }
                } else {
                    throw new BusinessException(String.format("Task1 error :【%s】", jsonObject.getString("msg")));
                }
            }
            start_time = DateUtil.plusSeconds(end_time, 1);

            List<Captain16Dto> captain16Dtos = jsonArray.toJavaList(Captain16Dto.class);
            List<Captain17Dto> captain17DtoList = getRecord(captain16Dtos);

            captain16Service.insertBatch(captain16Dtos, captain17DtoList);
            maycariRedis.set(dataKey, start_time);
        }


    }

    private List<Captain17Dto> getRecord(List<Captain16Dto> captain16Dtos) {
        TreeMap<String, String> params = new TreeMap<>();
        List<Captain17Dto> list = new ArrayList<>();
        for (Captain16Dto captain16Dto : captain16Dtos) {
            ThreadUtil.sleep(1000);
            params.clear();
            params.put("OrderId", String.valueOf(captain16Dto.getId()));
            String result = CaptainBIUtil.sendRequest(action2, params);
            JSONObject jsonObject = JSON.parseObject(result, Feature.OrderedField);
            JSONArray data = jsonObject.getJSONArray("data");
            if (data != null && data.size() > 0) {
                list.addAll(data.toJavaList(Captain17Dto.class));
            }
        }
        return list;
    }


    @Override
    public void run(ApplicationArguments args) throws Exception {
        //getData();
    }
}
